Micron Document




Java syntax
part 14/46 · 86.7 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true. Since J2SE 5.0, Java has four forms of such statements. The condition must have type boolean or Boolean, meaning C's

while (1) {
doSomething();
}

results in a compilation error.

while loop

In the while loop, the test is done before each iteration.

while (i < 10) {
doSomething();
}

do ... while loop

In the do ... while loop, the test is done after each iteration. Consequently, the code is always executed at least once.

// doSomething() is called at least once
do {
doSomething();
} while (i < 10);

for loop

for loops in Java include an initializer, a condition and a counter expression. It is possible to include several expressions of the same kind using comma as delimiter (except in the condition). However, unlike C, the comma is just a delimiter and not an operator.

for (int i = 0; i < 10; i++) {
doSomething();
}
// A more complex loop using two variables
for (int i = 0, j = 9; i < 10; i++, j -= 3) {
doSomething();
}

Like C, all three expressions are optional. The following loop is infinite:

for (;;) {
doSomething();
}

Enhanced for loop

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────